//
//  XGGroupTableViewController.m
//  HuanXin
//
//  Created by monkey on 2019/12/1.
//  Copyright © 2019 itcast. All rights reserved.
//

#import "XGGroupTableViewController.h"

#import "XGItemTableViewCell.h"
#import "XGIndexHeaderFooterView.h"

#import "XGItemModel.h"

@interface XGGroupTableViewController ()
{
    /// 头部数据
    NSArray<XGItemModel *> *_headerItems;
    /// 索引分组
    NSMutableArray<NSString *> *_indexArrM;
    /// 内容数据
    NSMutableArray<NSMutableArray<XGItemModel *> *> *_sectionsArrM;
}

@end

@implementation XGGroupTableViewController

#pragma mark - 公开方法

/// 头部数据
- (NSArray<XGItemModel *> *)headerItems
{
    return @[];
}
/// 内容数据
- (NSArray<XGItemModel *> *)contentItems
{
    return @[];
}

- (void)reloadTableView
{
    [_indexArrM removeAllObjects];
    [_sectionsArrM removeAllObjects];
    
    [self sectionsList:[self contentItems] sortKeyWordName:@"title"];
    [self.tableView reloadData];
}

- (void)leftSlideDeleteAction:(NSString *)name completion:(void (^)(void))completion
{
    
}

#pragma mark - 控制器生命周期方法

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 设置tableView
    [self setUpTableView];
    _headerItems = [self headerItems];
    [self sectionsList:[self contentItems] sortKeyWordName:@"title"];
}

#pragma mark - 数据源和代理方法

// 多少组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _indexArrM.count;
}

// 每组多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return (section == 0 ? _headerItems.count : _sectionsArrM[section].count);
}

// 每行的cell视图
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XGItemTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([XGItemTableViewCell class])];
    XGItemModel *itemModel = indexPath.section == 0 ? _headerItems[indexPath.row] : _sectionsArrM[indexPath.section][indexPath.item];
    cell.itemModel = itemModel;
    return cell;
}

// 组头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return (section == 0 ? 0.0 : 30.0);
}

// 组头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    }
    
     XGIndexHeaderFooterView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass([XGIndexHeaderFooterView class])];
    headerView.title = _indexArrM[section];
    return headerView;
}

// 索引
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return _indexArrM;
}

// 是否可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return indexPath.section != 0;
}

// cell左滑删除按钮的标题
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

// 左滑cell
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self alertWithTitle:@"确定要删除吗?" message:nil destructiveTitle:@"确定" destructiveAction:^(UIAlertAction * _Nullable action) {
            [self leftSlideDeleteAction:self->_sectionsArrM[indexPath.section][indexPath.row].title completion:^{
                if (self->_sectionsArrM[indexPath.section].count == 1) {
                    [self->_sectionsArrM removeObjectAtIndex:indexPath.section];
                    [self->_indexArrM removeObjectAtIndex:indexPath.section];
                    [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
                    
                } else {
                    [self->_sectionsArrM[indexPath.section] removeObjectAtIndex:indexPath.row];
                    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
                }
            }];
        } defaultTitle:@"取消" defaultAction:nil];
    }
}

// 点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    XGItemModel *itemModel = indexPath.section == 0 ? _headerItems[indexPath.row] : _sectionsArrM[indexPath.section][indexPath.item];
    if (itemModel.selectedCallBlock) {
        itemModel.selectedCallBlock(itemModel.title);
    }
}

#pragma mark - 其他方法

- (void)setUpTableView
{
    self.tableView.tintColor = [UIColor red:31 green:185 blue:34 alpha:1.f];
    self.tableView.rowHeight = 64.0;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.separatorInset = UIEdgeInsetsZero;
    [self.tableView registerClass:[XGItemTableViewCell class] forCellReuseIdentifier:NSStringFromClass([XGItemTableViewCell class])];
    [self.tableView registerClass:[XGIndexHeaderFooterView class] forHeaderFooterViewReuseIdentifier:NSStringFromClass([XGIndexHeaderFooterView class])];
}

// 设置分组索引
- (void)sectionsList:(NSArray<XGItemModel *> *)objects sortKeyWordName:(NSString *)sortKeyWordName
{
    // 1.建立索引的核心, 返回27，是a－z和＃
    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
    // 索引数目
    NSInteger sectionTitlesCount = [collation sectionTitles].count;
    
    // 2.为每个索引建立一个数组 用来存放组内数据
    NSMutableArray<NSMutableArray<XGItemModel *> *> *mutableSections = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
    for (NSUInteger idx = 0; idx < sectionTitlesCount; idx++) {
        [mutableSections addObject:[NSMutableArray array]];
    }
    
    // 3.将对象插入到对应索引的数组中
    for (id object in objects) {
        NSInteger sectionNumber = [collation sectionForObject:object collationStringSelector:NSSelectorFromString(sortKeyWordName)];
        [mutableSections[sectionNumber] addObject:object];
    }
    
    // 4.对索引内的分组数据进行排序
    for (NSUInteger idx = 0; idx < sectionTitlesCount; idx++) {
        [mutableSections[idx] sortUsingComparator:^NSComparisonResult(XGItemModel *obj1, XGItemModel *obj2) {
            return [obj1.title compare:obj2.title];
        }];
    }
    
    // 5.建立标题索引
    NSMutableArray *existTitles = [NSMutableArray array];
    NSArray *allSections = [collation sectionIndexTitles];
    for (NSUInteger i = 0; i < allSections.count; i++) {
        if ([mutableSections[i] count] > 0) {
            [existTitles addObject:allSections[i]];
        }
    }
    
    // 6.删除数据为空的联系人分组
    NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
    [mutableSections enumerateObjectsUsingBlock:^(NSArray *section, NSUInteger idx, BOOL * _Nonnull stop) {
        if (section.count == 0) {
            [indexSet addIndex:idx];
        }
    }];
    [mutableSections removeObjectsAtIndexes:indexSet];
    
    _indexArrM = existTitles;
    [_indexArrM insertObject:@"#" atIndex:0];
    _sectionsArrM = mutableSections;
    [_sectionsArrM insertObject:[NSMutableArray array] atIndex:0]; // 添加一个空数组防止索引不对齐
}

@end
